#include "cutdatamodel.h"
CutDataModel* CutDataModel::m_instance = nullptr;

CutDataModel::CutDataModel(QObject *parent)
    : QAbstractListModel(parent)
{
    qDebug() << "CutDataModel instance created";
    // 获取应用数据目录，确保路径存在
    // 获取当前程序所在目录（可执行文件所在路径）
    QString appDir = QCoreApplication::applicationDirPath();
    // 拼接CSV文件名，完整路径为：程序目录/save.csv
    m_csvFilePath = appDir + QDir::separator() + "save.csv";

    // 调试输出路径，方便确认
    qDebug() << "CSV文件保存路径：" << m_csvFilePath;
}

CutDataModel::~CutDataModel()
{
    qDebug() << "CutDataModel instance destroyed";
    m_instance = nullptr;
}

CutDataModel* CutDataModel::getInstance()
{
    if (!m_instance) {
        m_instance = new CutDataModel(); // 使用应用程序作为父对象
    }
    return m_instance;
}

int CutDataModel::rowCount(const QModelIndex &parent) const
{
    if (parent.isValid())
        return 0;

    return m_dataList.count();
}

QVariant CutDataModel::data(const QModelIndex &index, int role) const
{
    if (!index.isValid() || index.row() >= m_dataList.count())
        return QVariant();

    const cutData &data = m_dataList[index.row()];

    switch (role) {
    case OrderCodeRole: return data.orderCode;
    case ProfileTypeRole: return data.profileType;
    case ProductNameRole: return data.productName;
    case ColorRole: return data.color;
    case CutLengthRole: return data.cutLength;
    case CutCountRole: return data.cutCount;
    case MaterialLengthRole: return data.materialLength;
    case LeftAngleRole: return data.leftAngle;
    case RightAngleRole: return data.rightAngle;
    case WorkedCountRole: return data.workedCount;
    default: return QVariant();
    }
}

QHash<int, QByteArray> CutDataModel::roleNames() const
{
    QHash<int, QByteArray> roles;
    roles[OrderCodeRole] = "orderCode";
    roles[ProfileTypeRole] = "profileType";
    roles[ProductNameRole] = "productName";
    roles[ColorRole] = "materialcolor";
    roles[CutLengthRole] = "cutLength";
    roles[CutCountRole] = "cutCount";
    roles[MaterialLengthRole] = "materialLength";
    roles[LeftAngleRole] = "leftAngle";
    roles[RightAngleRole] = "rightAngle";
    roles[WorkedCountRole] = "workedCount";
    return roles;
}

bool CutDataModel::saveToCsv()
{
    QFile file(m_csvFilePath);
    // 打开文件（WriteOnly模式，覆盖原有内容）
    if (!file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        qWarning() << "无法打开CSV文件进行写入：" << file.errorString();
        return false;
    }

    QTextStream out(&file);
    // 写入CSV头部（字段名，方便识别）
    out << "订单编号,型材类型,产品名称,颜色,原料长度,切割长度,左角度,右角度,切割数量,已切数量\n";

    // 写入数据行
    for (const auto &data : m_dataList) {
        // 按字段顺序写入，用逗号分隔（注意：若字段含逗号需特殊处理，这里简化处理）
        out << data.orderCode << ","
            << data.profileType << ","
            << data.productName << ","
            << data.color << ","
            << data.materialLength << ","
            << data.cutLength << ","
            << data.leftAngle << ","
            << data.rightAngle << ","
            << data.cutCount << ","
            << data.workedCount << "\n";
    }

    file.close();
    qDebug() << "数据已保存到CSV：" << m_csvFilePath;
    return true;
}

bool CutDataModel::readFromCsv()
{
    QFile file(m_csvFilePath);
    if (!file.exists()) {
        qDebug() << "CSV文件不存在，无需读取：" << m_csvFilePath;
        return false;
    }

    // 打开文件（ReadOnly模式）
    if (!file.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qWarning() << "无法打开CSV文件进行读取：" << file.errorString();
        return false;
    }

    QTextStream in(&file);
    QVector<cutData> loadedData;

    // 跳过CSV头部（第一行）
    QString header = in.readLine();
    Q_UNUSED(header);

    // 逐行解析数据
    while (!in.atEnd()) {
        QString line = in.readLine();
        QStringList fields = line.split(","); // 按逗号分割字段

        // 检查字段数量是否匹配（10个字段）
        if (fields.size() != 10) {
            qWarning() << "CSV格式错误，跳过无效行：" << line;
            continue;
        }

        // 转换字段为cutData结构体
        cutData data;
        data.orderCode = fields[0];
        data.profileType = fields[1];
        data.productName = fields[2];
        data.color = fields[3];
        data.materialLength = fields[4].toDouble();
        data.cutLength = fields[5].toDouble();
        data.leftAngle = fields[6].toInt();
        data.rightAngle = fields[7].toInt();
        data.cutCount = fields[8].toInt();
        data.workedCount = fields[9].toInt();

        loadedData.append(data);
    }

    file.close();

    // 将加载的数据设置到模型
    setDataList(loadedData);
    qDebug() << "已从CSV加载" << loadedData.size() << "条数据";
    return true;
}

void CutDataModel::clearCsvFile()
{
    QFile file(m_csvFilePath);
    // 以WriteOnly模式打开（会清空文件）
    if (file.open(QIODevice::WriteOnly | QIODevice::Text)) {
        file.close();
        qDebug() << "CSV文件已清空：" << m_csvFilePath;
    } else {
        qWarning() << "无法清空CSV文件：" << file.errorString();
    }
}

QVariantMap CutDataModel::get(int index) const
{
    QVariantMap map;
    // 检查索引有效性
    if (index < 0 || index >= m_dataList.size()) {
        return map;
    }
    // 获取对应索引的cutData
    const cutData& data = m_dataList[index];
    // 填充map（键名需与QML中使用的属性名一致）
    map["orderCode"] = data.orderCode;
    map["profileType"] = data.profileType;
    map["productName"] = data.productName;
    map["materialcolor"] = data.color;
    map["materialLength"] = data.materialLength;
    map["cutLength"] = data.cutLength;
    map["leftAngle"] = data.leftAngle;
    map["rightAngle"] = data.rightAngle;
    map["cutCount"] = data.cutCount;
    map["workedCount"] = data.workedCount;
    return map;
}

void CutDataModel::incrementWorkedCount(int index)
{
    if (index < 0 || index >= m_dataList.size()) {
        return;
    }
    // 修改原始数据
    m_dataList[index].workedCount++;
    // 发送信号通知视图：index行的WorkedCountRole数据已更新
    emit dataChanged(createIndex(index, 0), createIndex(index, 0), {WorkedCountRole});
}

void CutDataModel::addData(const cutData &data)
{
    // QMutexLocker locker(&m_mutex);
    beginInsertRows(QModelIndex(), m_dataList.count(), m_dataList.count());
    m_dataList.append(data);
    endInsertRows();
    emit countChanged();
    emit modelDataUpdated(); // 通知数据更新
    clearCsvFile(); // 数据更新 → 清空CSV
}

void CutDataModel::setDataList(const QVector<cutData> &dataList)
{
    beginResetModel();
    m_dataList = dataList;
    endResetModel();
    emit countChanged();
    emit modelDataUpdated(); // 通知数据更新
    clearCsvFile(); // 数据更新 → 清空CSV
    qDebug() << "Data list updated. New count:" << m_dataList.count();
}

void CutDataModel::clear()
{
    beginResetModel();
    m_dataList.clear();
    endResetModel();
    emit countChanged();
    emit dataCleared();
    emit modelDataUpdated(); // 通知数据更新
    clearCsvFile(); // 数据更新 → 清空CSV
    qDebug() << "Data list cleared";
}

int CutDataModel::count() const
{
    // QMutexLocker locker(&m_mutex);
    return m_dataList.count();
}

void CutDataModel::setCount(int newCount)
{
    if (m_count == newCount)
        return;
    m_count = newCount;
    emit countChanged();
}
